import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import mysql.connector
import numpy as np

from mysql.connector import Error
from PIL import Image, ImageTk
import cv2
import os



# 获取当前Python文件的绝对路径
current_script_path = os.path.abspath(__file__)
# 获取当前Python文件所在的目录
current_directory = os.path.dirname(current_script_path)

# 数据库配置信息
DB_CONFIG = {
    'host': '111.229.122.184',
    'user': 'root',
    'password': 'Li2438881592?',  # 替换为你的MySQL密码
    'database': 'fruit_rat'  # 替换为你的数据库名
}

# 连接到数据库
def connect_to_db():
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        return conn
    except Error as e:
        print(f"连接数据库失败: {e}")
        return None


# 查询item_type为1的所有记录
def fetch_items():
    conn = connect_to_db()
    if conn is not None:
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM items WHERE item_type = 1 ORDER BY item_id ASC")
        items = cursor.fetchall()
        cursor.close()
        conn.close()
        return items
    return []


# 更新RuleIntroPage类以包含数据库逻辑
class RuleIntroPage:
    def __init__(self, master):
        self.master = master
        self.frame = ttk.Frame(self.master)
        self.frame.pack(fill="both", expand=True)
        self.groups = []
        self.update_groups()

    def update_groups(self):
        items = fetch_items()
        for group_frame in self.groups:
            group_frame.destroy()
        self.groups = []

        # 计算组的横向起始位置，使其在窗口中间显示
        start_x = (self.master.winfo_width() - 0.8 * self.master.winfo_screenwidth()) // 2

        for item in items:
            group_frame = ttk.Frame(self.frame)
            group_frame.pack(fill="x", padx=start_x, pady=10)
            self.groups.append(group_frame)

           # 左侧图片
            img_path = item[3]
            print("img_path:" + img_path)
            img_path_full = current_directory + img_path # 正确连接目录和文件名
            print("图片完整路径:", img_path_full)

            try:
                # 使用PIL的Image.open直接读取图片
                img = Image.open(img_path_full)
                img = img.resize((100, 100))
                img_photo = ImageTk.PhotoImage(img)
            except IOError as e:
                print(f"Error loading image: {e}")
                continue

            # 左侧图片
            imgLabel = tk.Label(group_frame, image=img_photo)  # 把图片整合到标签类中
            imgLabel.image = img_photo  # 保持对图片的引用
            imgLabel.pack(side=tk.LEFT, padx=10, pady=10)  # 将图片放置在框架的左侧

            # 右侧文字
            text_label = tk.Label(group_frame, text=f"{item[2]}：{item[4]}", wraplength=680, font=("Arial", 35))
            text_label.pack(side="left", padx=10)